package com.yiwei.zxp.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.CommentSubmitBean;
import com.yiwei.zxp.api.bean.UploadImgBean;
import com.yiwei.zxp.api.bean.WithoutCommentGoodsBean;
import com.yiwei.zxp.api.model.ItemGoodsDetail;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.BuyerOrderNeedRefreshEvent;
import com.yiwei.zxp.event.UploadCommentImgEvent;
import com.yiwei.zxp.fragment.SendCommentFragment;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.ImageUtil;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.view.V19FrameLayout;
import com.yiwei.zxp.view.uploadImage.UploadImgAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SendEvaluateActivity extends BaseActivity {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.cb_check)
    ImageView cbCheck;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.layout_contain)
    LinearLayout layoutContain;
    @BindView(R.id.btn_submit_more)
    SuperButton btnSubmitMore;
    private UploadImgAdapter uploadImgAdapter;
    private Unbinder unbiner;
    private List<CommentSubmitBean.ItemsBean> submitData;

    private boolean isNiMing = false;
    private String order_no;
    //    private ArrayList<ItemGoodsDetail> totalData;
    private int selectFragmentPoi = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate_send);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();

    }

    private void init() {
        order_no = getIntent().getStringExtra("order_no");
        txtTitle.setText("发布评价");
//        addFragment();
        getWithoutCommentGoods();
    }


    public void goToTakePhoto(int selectFragmentPoi) {
        this.selectFragmentPoi = selectFragmentPoi;
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (uploadImgAdapter == null) {
                    initUploadImgAdapter();
                }
                uploadImgAdapter.withMode(UploadImgAdapter.MODE_IMG).showDialog();
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void initUploadImgAdapter() {
        uploadImgAdapter = new UploadImgAdapter(this, new UploadImgAdapter.Action2() {
            @Override
            public void call(Bitmap file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(file);
                }
            }

            @Override
            public void callTake(File file, int mode) {
                if (mode == UploadImgAdapter.MODE_IMG) {
                    getUploadImg(ImageUtil.decodeUri(SendEvaluateActivity.this, Uri.parse(file.getAbsolutePath())));
                }
            }
        }, 1);
    }

    public void getUploadImg(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImg(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    savePath(result.datas.url);
                });
    }

    //    提交评价
    public void getCommentSubmit() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        CommentSubmitBean bean = new CommentSubmitBean();
        bean.order_no = order_no;
        bean.items = submitData;
        Api.api_service.getCommentSubmit(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new BuyerOrderNeedRefreshEvent());
                    ToastUtil.makeText(this, "评论成功");
                    finish();
                });
    }


    //    获取没有评价的商品
    public void getWithoutCommentGoods() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        WithoutCommentGoodsBean bean = new WithoutCommentGoodsBean();
        bean.order_no = order_no;

        Api.api_service.getWithoutCommentGoods(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setFragmentData(result.datas.items);
                });
    }

    public List<CommentSubmitBean.ItemsBean> getSubmitData() {
        return submitData;
    }

    private void setFragmentData(ArrayList<ItemGoodsDetail> totalData) {
        if (totalData != null && totalData.size() != 0) {
            submitData = new ArrayList<>();
            for (int i = 0; i < totalData.size(); i++) {
                CommentSubmitBean.ItemsBean bean = new CommentSubmitBean.ItemsBean();
                bean.goods_id = totalData.get(i).goods_id;
                bean.content = "";
                bean.anonym = "0";
                bean.score = "5";
                bean.photos = new ArrayList<>();
                submitData.add(bean);
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                SendCommentFragment fragment = new SendCommentFragment();
                fragment.setImage(totalData.get(i).photos);
                Bundle bundle = new Bundle();
                if (totalData.size() == 1) {
                    bundle.putBoolean("is_single", true);
                } else {
                    btnSubmitMore.setVisibility(View.VISIBLE);
                }
                bundle.putInt("id", i);
                fragment.setArguments(bundle);
                transaction.add(R.id.layout_contain, fragment);
                transaction.commit();
            }

        }
    }


    public void savePath(String path) {
        EventBus.getDefault().post(new UploadCommentImgEvent(selectFragmentPoi, path));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (uploadImgAdapter != null) {
            uploadImgAdapter.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }


    @OnClick({R.id.btn_back, R.id.cb_check})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.cb_check:
                isNiMing = !isNiMing;
                if (isNiMing) {
                    cbCheck.setImageResource(R.mipmap.img_check_box_check);
                    if (getSubmitData() != null && getSubmitData().size() != 0) {
                        getSubmitData().get(0).anonym = "1";
                    }
                } else {
                    cbCheck.setImageResource(R.mipmap.img_check_box_uncheck);
                    if (getSubmitData() != null && getSubmitData().size() != 0) {
                        getSubmitData().get(0).anonym = "0";
                    }
                }
                break;
        }
    }

    @OnClick({R.id.btn_submit, R.id.btn_submit_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
//                getCommentSubmit();
            case R.id.btn_submit_more:
                if (getSubmitData() != null && getSubmitData().size() != 0) {
                    for (int i = 0; i < getSubmitData().size(); i++) {
                        if (TextUtils.isEmpty(getSubmitData().get(i).content)) {
                            Dialog.showDefaultDialog(this, "", "还没有评价完商品是否决定提交？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                                @Override
                                public void confirm() {
                                    getCommentSubmit();
                                }

                                @Override
                                public void cancel() {

                                }
                            });
                            return;
                        }
                    }
                    getCommentSubmit();
                }

                break;
        }
    }
}
